import web, datetime
import json, time
import subprocess 

import os

import logging
import logging.handlers

my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address = '/dev/log')
my_logger.addHandler(handler)


def get_ips():
    ips = []
    for line in subprocess.check_output(["ifconfig"]).split("\n"):
        if "inet addr:" in line and not "127.0.0.1" in line:
            ips.append(line.split()[1].strip("addr:"))
    return ips

def get_hostname():
    return subprocess.check_output(["hostname"]).strip()

def get_file(filename):
    """ Get the contents of a file """
    filename = os.path.realpath(filename)
    if not os.path.isfile(filename):
        return ""
    with open(filename, "r") as f:
        return f.read()

def get_link_filename(filename):
    """ Get the contents of a file """
    filename = os.path.realpath(filename)
    return filename


# Cura 
def get_cura_configs():
    """ Get a list of config files """
    path = "/etc/cura/"
    blacklist = ["default.ini", "printer.ini", "local.ini"]
    try:
        files = [ f for f in os.listdir(path) if os.path.isfile(os.path.join(path,f)) and f not in blacklist  ]
        return files
    except OSError: 
        return []

def get_current_cura_config():
    """ Get the current printer """
    path = "/etc/cura/printer.ini"
    real = os.path.realpath(path)
    return real.split("/")[3]


def choose_cura_config(filename):
    """ Choose which cura config should be used """
    path = "/etc/cura/"
    whitelist = get_cura_configs()
    if filename not in whitelist:
        return False
    filename = os.path.join(path,filename)
    linkname = os.path.join(path,"printer.ini")
    # Only unlink if exists
    if os.path.isfile(linkname):
        os.unlink(linkname)
    # only link if exists
    if os.path.isfile(filename):
        os.symlink(filename, linkname)
        return True
    return False


def get_printers():
    """ Get a list of config files """
    path = "/etc/redeem/"
    blacklist = ["default.cfg", "printer.cfg", "local.cfg"]
    try:
        files = [ f for f in os.listdir(path) if os.path.isfile(os.path.join(path,f)) and f not in blacklist  ]
        return files
    except OSError: 
        return []

def get_current_printer():
    """ Get the current printer """
    path = "/etc/redeem/printer.cfg"
    real = os.path.realpath(path)
    return real.split("/")[3]


def choose_printer(filename):
    """ Choose which printer config should be used """
    path = "/etc/redeem/"
    whitelist = get_printers()
    if filename not in whitelist:
        return False
    filename = os.path.join(path,filename)
    linkname = os.path.join(path,"printer.cfg")
    # Only unlink if exists
    if os.path.isfile(linkname):
        os.unlink(linkname)
    # only link if exists
    if os.path.isfile(filename):
        os.symlink(filename, linkname)
        return True
    return False

def save_file(filename, content):
    """ Save the contents of a file """
    whitelist = [
        "/etc/redeem/local.cfg", 
        "/etc/cura/printer.ini"]
    #if filename not in whitelist:
    #    my_logger.critical("Error saving file "+filename)
    #    return False
    try:
        with open(filename, "w+") as f:
            f.write(content)
    except Error:
        return False
    return True

def send(self, msg):
    f = os.open("/dev/testing_1", os.O_RDWR)
    os.write(f, msg+"\n")
    while True:
        ret = self.readline(f)
        if "ok" in ret:
            break
        else:
            my_logger.critical("Got '"+ret+"'")
    os.close(f)
    return ret

def readline(self, f):
    message = ""
    while True:
        cur_char = os.read(f, 1)
        if (cur_char == '\n' or cur_char == ""):
            return message;
        message = message + cur_char

